﻿using System;
using System.Data;
using System.Data.SqlClient;
using NUnit.Framework;

namespace SqlTdd.Core.Model
{
    public class SqlTddTestMethod
    {
        public virtual Int64 Id { get; set; }
        public virtual string Name { get; set; }
        public virtual string TestSchema { get; set; }
        public virtual string TestSuite { get; set; }

        public virtual void Run(string connectionString)
        {
            SqlConnection sqlConn = null;
            try
            {
                sqlConn = new SqlConnection(connectionString);
                sqlConn.Open();

                var sqlCmd = new SqlCommand("[" + TestSchema + "].[" + Name + ']', sqlConn);
                sqlCmd.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                if (IsAssertionException(ex))
                {
                    throw new AssertionException(ex.Message, ex);
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                if (sqlConn != null && sqlConn.State != ConnectionState.Closed)
                    sqlConn.Close();
            }
        }

        private bool IsAssertionException(SqlException ex)
        {
            if (ex.Number == 50100)
                return true;
            else
                return false;
        }
    }
}